package org.feng.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class SpringBeanUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;


    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanUtils.applicationContext = applicationContext;
    }

    public static <T> T getByClass(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    public static <T> T getByClassAndAges(Class<T> clazz, Object... ages) {
        return applicationContext.getBean(clazz, ages);
    }

    public static <T> List<T> getBeansByType(Class<T> clazz) {
        Map<String, T> beansOfType = applicationContext.getBeansOfType(clazz);
        return new ArrayList<>(beansOfType.values());
    }

}
